<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Download extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function download() {
        $this->load->helper('download');
        $this->load->database();

        $playlist = $_POST['playlist'];
        $playlist_dir = utf8_decode($playlist);
        $description = $_POST['description'];
        $this->db->insert('playlist', array('name' => $playlist, 'description' => $description));
        $id_playlist = $this->db->insert_id();
        @mkdir('musics/' . $playlist_dir);
        
        $json = $_POST['json'];
        $musics = json_decode($json);
        $musics = $musics->tracks;
        
        //$count = 0;
        foreach ($musics as $music) {
            $name = $music->name;
            $artist = $music->artist->name;
            $album = $music->album->name;
            $url = $music->url;
            $file = $this->get_file_name($url);

            $result = $this->db->get_where('music', array('filename' => $file));

            if ($result->num_rows() == 0) {
                $m = array(
                    'name' => $name,
                    'artist' => $artist,
                    'album' => $album,
                    'filename' => $file
                );
                $this->db->insert('music', $m);
                $id_music = $this->db->insert_id();
                
                $this->save_music($url, 'musics/' . $playlist_dir . '/' . utf8_decode($artist) . ' - ' . utf8_decode($name) . '.mp3');
                
            }else{
                $music_result = $result->result();
                $music_bean = $music_result[0];
                $id_music = $music_bean->id_music;
                $name = $music_bean->name;
                $artist = $music_bean->artist;
                @file_put_contents( 'musics/' . $playlist_dir . '/' . utf8_decode($artist) . ' - ' . utf8_decode($name) . '.txt', "Música já inserida");
            }
            
            $this->db->insert('playlist_music', array('id_playlist' => $id_playlist, 'id_music' => $id_music));
            //if($count++ == 2) break;
        }
    }

    private function get_file_name($url) {
        $file = explode("/", $url);
        $file = $file[count($file) - 1];
        return $file;
    }

    private function save_music($url, $file_path) {
        $data = file_get_contents($url);
        file_put_contents($file_path, $data);
    }

}

/* End of file welcome.php */
/* Location: ./application/controllers/download.php */